<?php
/**
 * Unique Column Rule
 * This rule makes sure that the value doesn't already exist in
 * a specific column of a specific table.
 *
 * @package VisiCommerce
 * @subpackage Validation Rules
 * @author Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright (c) 2010 Luke Visinoni <luke.visinoni@gmail.com>
 * @version $Id$
 */
class Visi_Rule_UniqueColumn extends Q_Rule_Abstract {

    /**
     * The parameters that were passed to this rule
     * @param model The model object used to do the query
     * @param column The column that needs to be unique
     */
    protected $_params = array(
        'model' => null,
        'column' => null,
    );
    
    public function isValid($value) {
    
        $column = $this->getParam('field');
        if (!$model = $this->getParam('model')) {
            if (!is_null($this->_set) && $this->_set instanceof Visi_Rule_ModelSet) {
                $model = $this->_set->getModel();
            } else {
                throw new Q_Rule_Exception(get_class($this) . ' requires that you provide a model parameter.');
            }
        }
        if ($model instanceof Visi_Db_Table) {
            if (is_null($value)) {
                return false;
            }
            $select = $model->select()->where("$column = ?", $value);
            if ($primary = $model->info(Zend_Db_Table_Abstract::PRIMARY)) {
                $primary = (array) $primary;
            }
            if (empty($primary)) {
                throw new Q_Rule_Exception(get_class($this) . ' requires a model with a primary key.');
            }
            if (count($primary) > 1) {
                throw new Q_Rule_Exception(get_class($this) . ' does not yet support multiple primary keys.');
            }
            $primary = $primary[1];
            if ($row = $this->_set->getRow()) {
                if ($row->$primary) {
                    $select->where("$primary <> ?", $row->$primary);
                }
            }
            if (!$row = $model->fetchRow($select)) {
                return true;
            }
        }
        return false;
    
    }
    
}
